<?php
class Home extends CI_Controller {
	function __construct() {
		parent::__construct();
		if ($this->session->userdata("logged") == "1") {
			$this->load->view('dashboard');
		} elseif ($this->session->userdata("logged") == "0") {
			$this->load->view('startpage');
		}
	}
	function index() {
	}
	function dashboard() {
		$this->load->view('dashboard');
	}
	function register() {
		$this->load->view('register');
	}
	function startpage() {
		$this->load->view('startpage');
	}
	function kill_sess() {
		$array_items = array('UserID' => '', 'email' => '', 'logged' => '');
		$this->session->unset_userdata($array_items);
		redirect("/home/startpage/", 'location');
	}
	function logsig() {
		// TODO: check db to make sure that $idgen isn't already a number in the table
			// cannot register a new account multiple times within a timeframe
		$idgen = uniqid(rand(), false);
		$this->load->library('encrypt');
		header('Content-type:application/json');
		$postedEmail = $this->input->post('email');
		$password = $this->input->post('password');
		$hashedPass = $this->encrypt->sha1($password);
		$query = $this->db->query("SELECT * FROM users WHERE UsersId = '{$postedEmail}' AND Email = '{$postedEmail}' AND Password = '{$hashedPass}'");
		if ($query->num_rows() > 0) { // if user is already registered, execute the following sql/php commands.
			$row = $query->row();
			$this->session->set_userdata('email',  $postedEmail);
			$this->session->set_userdata('logged', "1"); // 1 means user is logged in.
			$json1 = json_encode(array('session_state' => true));
			echo $json1;
		} else {
			$query = $this->db->query("INSERT IGNORE INTO users (userpid, Email, Password, dateTimeRegistered, isLeader) VALUES ('{$idgen}', '{$postedEmail}', '{$hashedPass}', NOW(), '0')");
				$query = $this->db->query("SELECT * FROM users WHERE isLeader LIKE '%1%'");
				if ($query->num_rows() > 0) {
					$row = $query->row();
					if ($row->isLeader == '1') {
						$leader_id = $row->UsersId;
						$id_selector = $this->db->query("SELECT userpid FROM users");
						$row1 = $query->row();
						$user_id = $row->userpid;
						$this->db->query("INSERT IGNORE INTO friends (node1id, node2id, friends_since, friend_type)
						VALUES('{$leader_id}', '{$user_id}', NOW(), 'plus')");
						}
				}
			$this->session->set_userdata('UserPID', $idgen);
				}
			$json2 = json_encode(array('session_state' => false));
			}
	}
?>